<?php

$script_dir = dirname( __FILE__ );

require_once( "$script_dir/Models.php" );

class SpecialGridTestVerify extends SpecialPage {
    function __construct() {
        parent::__construct( 'GridTest' );
        wfLoadExtensionMessages( 'GridTest' );
    }

    private $manually_corrected_types = array(
        'longtext',
    );

    function execute( $par ) {
        global $wgRequest, $wgOut, $script_dir;

        $this->setHeaders();

        ob_start();
        if( !$wgRequest->getVal( 'test' ) ) {
            $allTests = gtGetUsersWithActiveTests();
            require( "$script_dir/templates/test_verify_special/all.php" );
        } else {
            $test = gtGetTest( $wgRequest->getVal( 'test' ) );
            $answers_given = array();
            foreach( $test['answers'] as $answer ) {
                $answers_given[$answer['question_id']][] = $answer['value'];
            }
            $points = array();
            $test_verified = true;
            for( $i=0; $i<count( $test['questions'] ); $i++ ) {
                if( in_array( trim( $test['questions'][$i]['modifiers']['tip'] ),
                    $this->manually_corrected_types ) ) {

                    $points[] = -1; // manually corrected question
                    $test_verified = false; 
                } else {
                    $points[] = $this->question_points( $test['questions'][$i], $answers_given[$i] );
                }
            }

            require( "$script_dir/templates/test_verify_special/test.php" );
        }
        $data = ob_get_clean();
        $wgOut->addHTML( $data );
    }

    function question_points( $question, $answers ) {
        $points = 0;
        foreach( $answers as $answer ) {
            foreach( $question['answers'] as $possible_answer ) {
                if( trim( $possible_answer['text'] ) == trim( $answer ) ) {
                    if( !$possible_answer['points'] ) {
                        return 0; // wrong answer
                    } else {
                        $points += $possible_answer['points'];
                    }
                    break;
                }
            }
        }
        return $points;
    }
}
